package com.mayikt.AuthUtil;


import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

@Component
public class WeChatAuthUtil {
    private String GET_WEIXIN_CODE_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={}&redirect_uri={}&response_type=code&scope=snsapi_userinfo&state={}#wechat_redirect";
    private String GET_WEIXIN_ACCESSTOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={}&secret={}&code={}&grant_type=authorization_code";
    private String GET_WEIXIN_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo?access_token={}&openid={}&lang=zh_CN";


    public String getAuthorizeURL(String appId, String redirectUrl, String state){
        String url = StrUtil.format(GET_WEIXIN_CODE_URL, appId,redirectUrl,state);
        return url;
    }

    public JSONObject getAccessTokenAndOpenIdByCode(String appId, String secret, String code){
        String url = StrUtil.format(GET_WEIXIN_ACCESSTOKEN_URL, appId,secret,code);
        JSONObject jsonObject = JSONObject.parseObject(HttpUtil.get(url));
        return jsonObject;
    }

    public JSONObject getUserInfo(String accessToken, String openId){
        String url = StrUtil.format(GET_WEIXIN_USERINFO_URL, accessToken,openId);
        JSONObject userInfo =JSONObject.parseObject(HttpUtil.get(url));
        return userInfo;
    }
}
